/* $RCSFile: EnhancedHtml.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/EnhancedHTML/EnhancedHtml.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:53  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

using AddonNice.Diagnostics;
using AddonNice.Core;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Settings.PageModules.EnhancedHtml;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.EnhancedHtml
{

    public class EStr
    {
        #region settings
        public const string ENHANCEDHTML_SHOWTITLEPAGE              =   "ENHANCEDHTML_SHOWTITLEPAGE";
		public const string ENHANCEDHTML_SHOWUPMENU                 =   "ENHANCEDHTML_SHOWUPMENU";
		public const string ENHANCEDHTML_ALIGNUPMENU                =   "ENHANCEDHTML_ALIGNUPMENU";
		public const string ENHANCEDHTML_SHOWDOWNMENU               =   "ENHANCEDHTML_SHOWDOWNMENU";
		public const string ENHANCEDHTML_ALIGNDOWNMENU              =   "ENHANCEDHTML_ALIGNDOWNMENU";
		public const string ENHANCEDHTML_ADDINVARIANTCULTURE        =   "ENHANCEDHTML_ADDINVARIANTCULTURE";
		public const string ENHANCEDHTML_SHOWMULTIMODE              =   "ENHANCEDHTML_SHOWMULTIMODE";
		public const string ENHANCEDHTML_GET_CONTENTS_FROM_PORTALS  =   "ENHANCEDHTML_GET_CONTENTS_FROM_PORTALS";
        #endregion settings

        #region localized resources string
        public const string ENHANCEDHTML_CONFIRMDELETEMESSAGE       =   "ENHANCEDHTML_CONFIRMDELETEMESSAGE";
        public const string ENHANCEDHTML_SHOWALLPAGES               =   "ENHANCEDHTML_SHOWALLPAGES";
        public const string ENHANCEDHTML_NEWPAGE                    =   "ENHANCEDHTML_NEWPAGE";
        public const string ENHANCEDHTML_EDITPAGE                   =   "ENHANCEDHTML_EDITPAGE";
        public const string ENHANCEDHTML_DELETEPAGE                 =   "ENHANCEDHTML_DELETEPAGE";
        public const string ENHANCEDHTML_RETURN                     =   "ENHANCEDHTML_RETURN";
        public const string ENHANCEDHTML_UPDATE                     =   "ENHANCEDHTML_UPDATE";
        public const string ENHANCEDHTML_CANCEL                     =   "ENHANCEDHTML_CANCEL";
        public const string HTML_DESKTOP_CONTENT                    =   "HTML_DESKTOP_CONTENT";
        public const string ENHANCEDHTML_SELECT_MODULE              =   "ENHANCEDHTML_SELECT_MODULE";
        public const string ENHANCEDHTML_SELECT_MODULE_PORTAL       =   "ENHANCEDHTML_SELECT_MODULE_PORTAL";
        public const string ENHANCEDHTML_MULTIPAGEMODE              =   "ENHANCEDHTML_MULTIPAGEMODE";
        public const string ENHANCEDHTML_PAGE                       =   "ENHANCEDHTML_PAGE"; 
        public const string ENHANCEDHTML_OF                         =   "ENHANCEDHTML_OF"; 
        public const string ENHANCEDHTML_SINGLEPAGEMODE             =   "ENHANCEDHTML_SINGLEPAGEMODE"; 
        public const string LEFT                                    =   "LEFT"; 
        public const string CENTER                                  =   "CENTER"; 
        public const string RIGHT                                   =   "RIGHT";
        #endregion localized resources string
    }

    /// <summary>
    /// Initializer class for EnhancedHtml 
    /// </summary>
    public class EnhancedHtmlSI : PortalModuleControlSI
    {
        public EnhancedHtmlSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]EnhancedHtmlSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]EnhancedHtmlSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]EnhancedHtmlSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                           =   pm.ExtendedResourcesGroup;
			SettingItemGroup _Group;

			#region Module Settings
			_Group                                      =   SettingItemGroup.MODULE_SPECIAL_SETTINGS;

			HtmlEditorDataType.AddEditorToSettings(bSettings, _Group,extgrp);

			SettingItemSpecial ShowTitlePage	        =   new SettingItemSpecial(EStr.ENHANCEDHTML_SHOWTITLEPAGE,new BooleanDataType());
			ShowTitlePage.Value					        =   StStr.strFalse;
			ShowTitlePage.Order					        =   10;
			ShowTitlePage.ExtendedGroupName             =   extgrp;
			ShowTitlePage.EnglishName			        =   "Show Title Page?";
			ShowTitlePage.Description			        =   "Mark this if you like see the Title Page";
			bSettings.AddSetting(ShowTitlePage);

			SettingItemSpecial ShowUpMenu               =   new SettingItemSpecial(EStr.ENHANCEDHTML_SHOWUPMENU,new BooleanDataType());
			ShowUpMenu.Value					        =   StStr.strFalse;
			ShowUpMenu.Order					        =   20;
			ShowUpMenu.ExtendedGroupName                =   extgrp;
			ShowUpMenu.EnglishName				        =   "Show Index Menu";
			ShowUpMenu.Description				        =   "Mark this if you like see a index menu whith the titles of all pages";
			bSettings.AddSetting(ShowUpMenu);

			ArrayList alignUpMenu				        =   new ArrayList();
			alignUpMenu.Add(new SettingOption(1, LocalizeHelper.Localize(EStr.LEFT,"Left")));  
			alignUpMenu.Add(new SettingOption(2, LocalizeHelper.Localize(EStr.CENTER,"Center")));
			alignUpMenu.Add(new SettingOption(3, LocalizeHelper.Localize(EStr.RIGHT,"Right")));

			SettingItemSpecial labelAlignUpMenu		    =   new SettingItemSpecial(EStr.ENHANCEDHTML_ALIGNUPMENU,new CustomListDataType(alignUpMenu, "Name", "Val"));
			labelAlignUpMenu.Description		        =   "Select here the align for index menu";
			labelAlignUpMenu.EnglishName		        =   "Align Index Menu";
			labelAlignUpMenu.Value				        =   "1";
			labelAlignUpMenu.Order				        =   30;
			labelAlignUpMenu.ExtendedGroupName          =   extgrp;
			bSettings.AddSetting(labelAlignUpMenu);

			SettingItemSpecial ShowDownMenu			    =   new SettingItemSpecial(EStr.ENHANCEDHTML_SHOWDOWNMENU,new BooleanDataType());
			ShowDownMenu.Value					        =   StStr.strTrue;
			ShowDownMenu.Order					        =   40;
			ShowDownMenu.ExtendedGroupName              =   extgrp;
			ShowDownMenu.EnglishName			        =   "Show Navigation Menu";
			ShowDownMenu.Description			        =   "Mark this if you like see a navigation menu with previous and next page";
			bSettings.AddSetting(ShowDownMenu);

			ArrayList alignDownMenu				        =   new ArrayList();
			alignDownMenu.Add(new SettingOption(1, LocalizeHelper.Localize(EStr.LEFT,"Left")));
			alignDownMenu.Add(new SettingOption(2, LocalizeHelper.Localize(EStr.CENTER,"Center")));
			alignDownMenu.Add(new SettingOption(3, LocalizeHelper.Localize(EStr.RIGHT,"Right")));

			SettingItemSpecial labelAlignDownMenu	    =   new SettingItemSpecial(EStr.ENHANCEDHTML_ALIGNDOWNMENU,new CustomListDataType(alignDownMenu, "Name", "Val"));
			labelAlignDownMenu.Description		        =   "Select here the align for index menu";
			labelAlignDownMenu.EnglishName		        =   "Align Navigation Menu";
			labelAlignDownMenu.Value			        =   "3";
			labelAlignDownMenu.Order			        =   50;
			labelAlignDownMenu.ExtendedGroupName        =   extgrp;
			bSettings.AddSetting(labelAlignDownMenu);

			SettingItemSpecial AddInvariant			    =   new SettingItemSpecial(EStr.ENHANCEDHTML_ADDINVARIANTCULTURE,new BooleanDataType());
			AddInvariant.Value					        =   StStr.strTrue;
			AddInvariant.Order					        =   60;
			AddInvariant.ExtendedGroupName              =   extgrp;
			AddInvariant.EnglishName			        =   "Add Invariant Culture";
			AddInvariant.Description			        =   "Mark this if you like see pages with invariant culture after pages with actual culture code";
			bSettings.AddSetting(AddInvariant);

            SettingItemSpecial ShowMultiMode	        =   new SettingItemSpecial(EStr.ENHANCEDHTML_SHOWMULTIMODE,new BooleanDataType());
			ShowMultiMode.Value					        =   StStr.strTrue;
			ShowMultiMode.Order					        =   70;
			ShowMultiMode.ExtendedGroupName             =   extgrp;
			ShowMultiMode.EnglishName			        =   "Show Multi-Mode icon";
			ShowMultiMode.Description			        =   "Mark this if you like see icon multimode page";
			bSettings.AddSetting(ShowMultiMode);


			SettingItemSpecial GetContentsFromPortals	=   new SettingItemSpecial(EStr.ENHANCEDHTML_GET_CONTENTS_FROM_PORTALS,new BooleanDataType());
			GetContentsFromPortals.Value		        =   StStr.strFalse;
			GetContentsFromPortals.Order		        =   80;
			GetContentsFromPortals.ExtendedGroupName    =   extgrp;
			GetContentsFromPortals.EnglishName	        =   "Get contents from others Portals?";
			GetContentsFromPortals.Description	        =   "Mark this if you like get contents from modules in others portals in the same database";
			bSettings.AddSetting(GetContentsFromPortals);

			#endregion
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]EnhancedHtmlSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    /// <summary>
	/// Multipages Multilingual Html Module
	/// </summary>
	public partial class EnhancedHtml : PortalModuleControl 
	{

		#region private variables
		private string EnhPageID;
		private string modeID;
		private string currentModeURL;
		private string currentURL;
		private string currentMenuSeparator;
		private readonly string tokenModule = "#MODULE#";
		private readonly string tokenPortalModule = "#PORTALMODULE#";
		#endregion

        #region properties from request querystring

        int _requestModuleID    =   0;

        public int requestModuleID
        {
            get
            {
                if (_requestModuleID == 0)
                {
                    // Determine ModuleID if specified
                    if (!IsDesignMode)
                    {
                        string str      =   Request.Params[StStr.strModuleID];
                        if (!string.IsNullOrEmpty(str))
                        {
                            try
                            {
                                _requestModuleID = Int32.Parse(str);
                            }
                            catch(Exception ex) 
                            {
                                if (PageTraceSwitch.Sw.TraceError)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EnhancedHtml.ModuleID Parse ModuleID: {0}, ex : {1}", str, ex),PageTraceSwitch.Sw.Info);
                            }
                        }
                    }
                }
                if (PageTraceSwitch.Sw.TraceInfo)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[I]EnhancedHtml ModuleID PageID: {0}, ModuleID: '{1}'", PageID, _requestModuleID),PageTraceSwitch.Sw.Info);
                return _requestModuleID;
            }
        }
        
        #endregion properties from request querystring
        				
		public override Guid GuidID 
		{
			get
			{
				return new Guid("{875254B7-2471-491f-BAF8-4AFC261CC224}");
			}
		}

        #region CTor and Initializer
		public EnhancedHtml()
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]EnhancedHtml Ctor Called.",ModuleTraceSwitch.Sw.Info);
		}

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                         =   "ENHANCEDHTML";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new EnhancedHtmlSI(bSettings,this);
        }
        #endregion
		
		#region page load
		/// <summary>
		/// The Page_Load event handler on this User Control is
		/// used to render blocks of HTML or text to the page.  
		/// The text/HTML to render is stored in the EnhancedHtml 
		/// database table.  This method uses the AddonNice.EnhancedHtmlDB()
		/// data component to encapsulate all data functionality.
        /// Html code generated uses following class
        ///                         EnhancedHtmlTitlePage EnhancedHtmlTitlePage_{0}
        ///                         EnhancedHtmlLink EnhancedHtmlLink_{0}
        ///                         where {0} is Current Module Layout
		/// </summary>
		protected void Page_Load(object sender, System.EventArgs e) 
		{
			bool addInvariantCulture	    =   Settings[EStr.ENHANCEDHTML_ADDINVARIANTCULTURE].ToBool();
			bool showTitle				    =   Settings[EStr.ENHANCEDHTML_SHOWTITLEPAGE].ToBool();
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml Page_Load BEG addInvariantCulture: {0}, showTitle: {1}", addInvariantCulture,showTitle),ModuleTraceSwitch.Sw.Info);
			// Get parameteres from request or cookies
			SetParameters ();
			// Get pages from DB
			DataTable PagesTb			    =   giveMePages(addInvariantCulture);
			
			if (PagesTb.Rows.Count == 0) 
				return;

			int nbim					    =	0;
			if ( modeID == "1") 
			{
				#region render all pages
				string ehMultiPageMode      =   LocalizeHelper.Localize(EStr.ENHANCEDHTML_MULTIPAGEMODE, "Multi Page Mode");
				foreach (DataRow contentPg in PagesTb.Rows)
				{
					Content				    =   contentPg["DesktopHtml"];
					int i				    =   int.Parse((string) contentPg[StStr.strItemID]);
					if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml Page_Load  Mode==1 i: {0}, Content:{1}", i,Content),ModuleTraceSwitch.Sw.Info);

					StringBuilder sb	    =	new	StringBuilder();
                    string fmt1             =   string.Format("<table width='100%' class='EnhancedHtmlTablePage EnhancedHtmlTablePage_{0}'><tr>",CurrentModulesLayout.Name);
					sb.Append(fmt1);
					
					if (showTitle)
					{
                        /// we add a class which references current theme
                        const string fmt2   =   "<td width='100%' align='left'><span class='EnhancedHtmlTitlePage EnhancedHtmlTitlePage_{0}'>{1}</span><hr /></td>";
						sb.AppendFormat(fmt2,CurrentModulesLayout.Name,contentPg["Title"]);
					}
					// Not show navigation in Print Page
					if (PagesTb.Rows.Count > 1 && !this.NamingContainer.ToString().Equals("ASP.print_aspx")) 
					{
                        const string fmt3   =   "<td align='right'><a href={0}>";
						sb.AppendFormat(fmt3,giveMeUrl("&ModeID=0&EnhPageID=" + contentPg[StStr.strItemID]));
                        const string fmt4   =   "<asp:Image ID='Image_{0}' SkinID='multipage' runat='server' AlternateText='{1}' BorderWidth='0' /></a></td>";
						sb.AppendFormat(fmt4,nbim++,ehMultiPageMode);
					}
                    const string fmt5       =   "</tr></table>";
					sb.Append(fmt5);
					string aux              =	sb.ToString();
					if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml Page_Load ModeID==1 aux:{0}", aux),ModuleTraceSwitch.Sw.Info);
					HtmlHolder.Controls.Add(ParseControl(aux));
					HtmlHolder.Controls.Add(toShow(Content.ToString()));
					HtmlHolder.Controls.Add(ParseControl("<br />"));
				}
				#endregion
			}
			else 
			{
				#region render selected page
				
                bool showMultiMode          =   Settings[EStr.ENHANCEDHTML_SHOWMULTIMODE].ToBool() && PagesTb.Rows.Count > 1;
				bool showUpmenu	            =   Settings[EStr.ENHANCEDHTML_SHOWUPMENU].ToBool() && PagesTb.Rows.Count > 1;
				bool showDownmenu           =   Settings[EStr.ENHANCEDHTML_SHOWDOWNMENU].ToBool() && PagesTb.Rows.Count > 1;

				// Not show navigation in Print Page
				if (this.NamingContainer.ToString().Equals("ASP.print_aspx")) 
				{
					showMultiMode           =   false;
					showUpmenu              =   false;
					showDownmenu            =   false;
				}
				string alignUpmenu		    =   giveMePosition(Settings[EStr.ENHANCEDHTML_ALIGNUPMENU].ToString());
				string alignDownmenu	    =   giveMePosition(Settings[EStr.ENHANCEDHTML_ALIGNDOWNMENU].ToString());
				string upmenu			    =   string.Empty;
				string downmenu			    =   string.Empty;
				string title			    =   string.Empty;
				string buffer			    =   string.Empty;
				string refs				    =   string.Empty;
				string prevRef			    =   string.Empty;
				string nextRef			    =   string.Empty;
				int i;
				int totalPages			    =   0;
				int actualPage			    =   -1;
				bool firstPg			    =   string.IsNullOrEmpty(EnhPageID);
				bool first				    =   true;
				string aux;

				string ehPage			    =   LocalizeHelper.Localize(EStr.ENHANCEDHTML_PAGE, "Page");
				string ehOf				    =   LocalizeHelper.Localize(EStr.ENHANCEDHTML_OF, "of");
				string ehSinglePageMode     =   LocalizeHelper.Localize(EStr.ENHANCEDHTML_SINGLEPAGEMODE, "Single Page Mode");
				
				foreach (DataRow contentPg in PagesTb.Rows)
				{
					i					    =   int.Parse((string)contentPg[StStr.strItemID]);
					if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml Page_Load  Mode!=1, i: {0}",i),ModuleTraceSwitch.Sw.Info);
					totalPages++;
					if (first)
					{
						first			    =   false;
					} 
					else
					{
						upmenu			    +=  currentMenuSeparator;
					}
					if (firstPg)
					{
						firstPg			    =   false;
						EnhPageID	        =   i.ToString();
					} 
					if ( ModuleTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml Page_Load  Mode!=1, i: {0}, EnhPageID: {1}",i,EnhPageID),ModuleTraceSwitch.Sw.Info);
					if ( i == int.Parse(EnhPageID) )
					{
						actualPage		    =   totalPages;
						buffer			    =   (string) contentPg["DesktopHtml"];
						title			    =   (string) contentPg["Title"];
						if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml Page_Load  Mode!=1, i: {0}, buffer: {1}, title: {2}",i,buffer,title),ModuleTraceSwitch.Sw.Info);
                        string fmt6         =   "<span class='EnhancedHtmlLink EnhancedHtmlLink_{0}'>{1}</span>";
						upmenu			    +=  string.Format(fmt6,CurrentModulesLayout.Name, title);
						if ( !string.IsNullOrEmpty(refs))
							prevRef		    =   refs;
					}
					else 
					{
                        const string fmt7   =   "<a href='{0}' class='EnhancedHtmlLink EnhancedHtmlLink_{1}'>{2}</a>";
						refs			    =   string.Format(fmt7,giveMeUrl("&ModeID=0&EnhPageID=" + i.ToString()),CurrentModulesLayout.Name,contentPg["Title"]);
						if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml Page_Load ModeID != 1 refs:{0}", refs),ModuleTraceSwitch.Sw.Info);
						upmenu			    +=  refs;
						if (totalPages - 1 == actualPage) 
						{
							nextRef		    =   refs;
						}
					}
				}
				if ( prevRef != string.Empty ) 
					downmenu	            +=  prevRef + currentMenuSeparator;
				downmenu		            +=  ehPage + " " + actualPage.ToString() + " " + ehOf + " " + totalPages.ToString();
				if (nextRef != string.Empty) 
					downmenu                +=  currentMenuSeparator + nextRef;
				StringBuilder sb	        =	new	StringBuilder();
                string tbstr                =   string.Format("<table width='100%' class='EnhancedHtmlTablePage EnhancedHtmlTablePage_{0}'><tr>",CurrentModulesLayout.Name);
				sb.Append(tbstr);
				if (showTitle)
				{
                    const string fmt1       =   "<td align='left'><p class='EnhancedHtmlTitlePage EnhancedHtmlTitlePage_{0}'>{1}</p></td>";
					sb.AppendFormat(fmt1,CurrentModulesLayout.Name,title);
					if (showMultiMode) 
					{
                        const string fmt2   =  "<td align='right'><a href={0}>";
						sb.AppendFormat(fmt2,giveMeUrl("&ModeID=1"));
                        const string fmt3   =  "<asp:Image ID='Image_{0}' SkinID='singlepage' runat='server' AlternateText='{1}' BorderWidth='0' /></a></td>";
						sb.AppendFormat(fmt3,nbim++,ehSinglePageMode);
					}
                    const string fmt4       =   "</tr><tr><td colspan='2'><hr /></td></tr><tr>";
					sb.Append(fmt4);
				}
				if ( showUpmenu && totalPages != 0 )
				{
					sb.AppendFormat("<td align='{0}'>{1}</td>",alignUpmenu,upmenu);
				}
				if (!showTitle && showMultiMode)
				{
                    const string fmt8       =   "<td align='right'><a href={0}>";
					sb.AppendFormat(fmt8,giveMeUrl("&ModeID=1"));
                    const string fmt9       =   "<asp:Image ID='Image_{0}' SkinID='singlepage' runat='server' AlternateText='{1}' BorderWidth='0' /></a></td>";
					sb.AppendFormat(fmt9,nbim++,ehSinglePageMode);
				}
				if (!sb.ToString().Equals(tbstr)) // If table is empty not add to the control
				{
                    const string fmt10      =   "</tr></table><br />";
					sb.Append(fmt10);
					aux			            =	sb.ToString();
					HtmlHolder.Controls.Add(ParseControl(aux));
				}
				HtmlHolder.Controls.Add(toShow(buffer));
				if (showDownmenu && totalPages != 0)
				{
                    const string fmt11      =   "<hr /><table width='100%'><tr><td align='{0}'>{1}</td></tr></table>";
					HtmlHolder.Controls.Add(new LiteralControl(string.Format(fmt11,alignDownmenu,downmenu)));
				}
				#endregion
			}
		}
		#endregion

		#region getContents to show
		private Control toShow (string text) 
		{
			int module                          =   0;
			if (text.StartsWith(tokenModule)) 
			{
				module                          =   int.Parse(text.Substring(tokenModule.Length));
			}
			else if (text.StartsWith(tokenPortalModule)) 
			{
				module                          =   int.Parse(text.Substring(tokenPortalModule.Length));
			}
			else return new LiteralControl(text);

			PortalModuleControl portalModule    =   null;
			string ControlPath                  =   string.Empty;
			SqlDataReader dr                    =   null;
			try
			{
				dr                              =   new ModulesDB().GetModuleDefinitionByID(module);
				if (dr.Read())
					ControlPath                 =   AddonNice.Settings.Path.ApplicationRoot + "/" + dr[StStr.DBDesktopSrc].ToString();
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EnhancedHtml toShow module: {0}, ex: {1}", module, ex),ModuleTraceSwitch.Sw.Info);
			}
			finally
			{
				if ( dr != null )
					dr.Close();
			}
			if (string.IsNullOrEmpty(ControlPath))
			{
				return new LiteralControl(string.Format("<br /><span class='Error'>Module '{0}' not found!</span><br />",module));
			}
			try
			{
				portalModule					=   (PortalModuleControl) Page.LoadControl(ControlPath);
				//Sets portal ID
				portalModule.PortalID			=   PortalID;
				ModuleConfiguration m			=   new ModuleConfiguration();           
				m.ModuleID						=   module;
				m.PageID						=   ModuleBaseConfiguration.PageID;
				m.PaneName						=   ModuleBaseConfiguration.PaneName;
				m.ModuleTitle					=   ModuleBaseConfiguration.ModuleTitle;
				m.AuthorizedEditRoles			=   string.Empty;
				m.AuthorizedViewRoles			=   string.Empty;
				m.AuthorizedAddRoles			=   string.Empty;
				m.AuthorizedDeleteRoles			=   string.Empty;
				m.AuthorizedPropertiesRoles		=   string.Empty;
				m.CacheTime						=   ModuleBaseConfiguration.CacheTime;
				m.ModuleOrder					=   ModuleBaseConfiguration.ModuleOrder;
				m.DesktopSrc					=   ControlPath;
                m.ModuleSettingsID              =   ModuleBaseConfiguration.ModuleSettingsID;
				portalModule.ModuleBaseConfiguration = m;

				portalModule.Settings[StStr.ModuleSettingsApplyModuleLayout].Value  = "false";
				portalModule.Settings[StStr.ModuleSettingsShowTitle].Value          = "false";
			}
			catch(Exception ex)
			{
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml toShow Unable to load control, module: {0}, copntrolPath: {1}, ex:{2}",module,ControlPath,ex),ModuleTraceSwitch.Sw.Info);
                const string ftm10  =   "<br /><span class='Error'>Unable to load control '{0}' !</span><br />";
				return new LiteralControl(string.Format(ftm10,ControlPath ));
			}
            
			portalModule.AddUrl				= string.Empty;       //Readonly
			portalModule.AddText			= string.Empty;      //Readonly
			portalModule.EditUrl			= string.Empty;      //Readonly
			portalModule.EditText			= string.Empty;     //Readonly
			portalModule.OriginalModuleID	= ModuleID;

			AddonNice.Settings.Cache.CurrentCache.Remove(AddonNice.Settings.Cache.Key.ModuleSettings(module));
			return portalModule;
		}
		#endregion

		#region select pages to show
		private void addPageRow (DataTable Tb, string item, string title, string content) 
		{
			DataRow contentPg			=   Tb.NewRow();
			contentPg[StStr.strItemID]	=   item;
			contentPg["Title"]			=   title;
			contentPg["DesktopHtml"]	=   Server.HtmlDecode(content);
			Tb.Rows.Add(contentPg);
		}		
		
		private DataTable giveMePages (bool addInvariantCulture)
		{
			bool selected				=   false;
			int selectedPage			=   -1;
			if (!string.IsNullOrEmpty(EnhPageID)) 
				selectedPage            =   int.Parse(EnhPageID);
			DataTable Tb				=   new DataTable("LocalizedPages");

			Tb.Columns.Add(new DataColumn("ItemID", typeof(string)));
			Tb.Columns.Add(new DataColumn("Title", typeof(string)));
			Tb.Columns.Add(new DataColumn("DesktopHtml", typeof(string)));

			EnhancedHtmlDB ehdb			=   new EnhancedHtmlDB();
			
			SqlDataReader dr	        =	null;
			try
			{
				dr                      =   ehdb.GetLocalizedPages(ModuleID, portalSettings.PortalUILanguage.LCID);
				while (dr.Read()) 
				{
                    string stritem      =   dr["ItemID"].ToString();
					addPageRow(Tb, stritem, (string) dr["Title"],(string) dr["DesktopHtml"]);
					if ( int.Parse(stritem) == selectedPage ) 
						selected        =   true;
				}
			}
			catch (Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml giveMePages ex:{0}", ex),ModuleTraceSwitch.Sw.Info);
			}
			finally
			{
				if ( dr != null )
					dr.Close();
			}

			if (Tb.Rows.Count == 0) 
			{
				if (portalSettings.PortalUILanguage.Parent.LCID != System.Globalization.CultureInfo.InvariantCulture.LCID)
				{
					SqlDataReader dr1	    =	null;
					try
					{
						dr1 = ehdb.GetLocalizedPages(ModuleID, portalSettings.PortalUILanguage.Parent.LCID);
						while (dr1.Read())
						{
                            string stritem  =   dr1["ItemID"].ToString();
							addPageRow(Tb, stritem, (string)dr1["Title"], (string)dr1["DesktopHtml"]);
							if ( int.Parse(stritem) == selectedPage )
								selected    =   true;
						}
					}
					catch (Exception ex)
					{
						if (ModuleTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml giveMePages GetLocalizedPages ex:{0}", ex),ModuleTraceSwitch.Sw.Info);
					}
					finally
					{
						if ( dr1 != null )
							dr1.Close();
					}
				}
			}
			
			if (addInvariantCulture || Tb.Rows.Count == 0)
			{
				SqlDataReader dr2	        =	null;
				try
				{
					dr2 = ehdb.GetLocalizedPages(ModuleID, System.Globalization.CultureInfo.InvariantCulture.LCID);
					while (dr2.Read())
					{
                        string stritem      =   dr2["ItemID"].ToString();
						addPageRow(Tb, stritem, (string)dr2["Title"], (string)dr2["DesktopHtml"]);
						if ( int.Parse(stritem) == selectedPage ) 
							selected        =   true;
					}
				}
				catch (Exception ex)
				{
					if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml giveMePages GetLocalizedPages 2 ex:{0}", ex),ModuleTraceSwitch.Sw.Info);
				}
				finally
				{
					if ( dr2 != null )
						dr2.Close();
				}
			}
			if (!selected ) 
				EnhPageID                   =   null;
			return Tb;
		}
		#endregion

		#region get/set initial parameters	
	
		/// <summary>
		/// Called from Page_Load to get parameters from request or cookies
		/// also set cookies if no parameters in request
		/// </summary>
		private void SetParameters ()
		{
			HttpCookie cookie1;
			DateTime time1;
			TimeSpan span1;
			int num1;
			string moduleCookie;
			bool moduleInUrl		=   requestModuleID == ModuleID;

			
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml SetParameters moduleInUrl: {0}", moduleInUrl),ModuleTraceSwitch.Sw.Info);


			currentMenuSeparator	=   " | ";
            // NB: The Path is the concatenation of the FilePath and the PathInfo trailer. For example, for the URL http://www.contoso.com/virdir/page.html/tail, the Path is /virdir/page.html/tail.
			currentURL				=   HttpUrlBuilder.BuildUrl(Page.Request.Path, PageID, ModuleID);
			currentURL				=   currentURL.Replace ("//", "/"); // TBC necessary after 1/6/09 ?

			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml SetParameters currentURL: {0}", currentURL),ModuleTraceSwitch.Sw.Info);

			if (moduleInUrl) 
			{
				if (Page.Request.Params["EnhPageID"] != null)
				{
					EnhPageID       =   Page.Request.Params["EnhPageID"].ToString();
				}
				else if (Page.Request.Params["ItemID"] != null)
				{
					EnhPageID       =   Page.Request.Params["ItemID"].ToString();
				}
			}
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml SetParameters EnhPageID: {0}", EnhPageID),ModuleTraceSwitch.Sw.Info);
			currentModeURL			=   currentURL;
			moduleCookie			=   "EnhancedHtml:" + ModuleID.ToString();
			modeID					=   "0";
			if (Page.Request.Params["ModeID"] != null)
			{
				modeID				=   Page.Request.Params["ModeID"].ToString();
				cookie1				=   new HttpCookie(moduleCookie);
				cookie1.Value		=   modeID;
				time1				=   DateTime.Now;
				span1				=   new TimeSpan (90, 0, 0, 0);
				cookie1.Expires		=   time1.Add(span1);
				base.Response.AppendCookie(cookie1);
				if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml SetParameters from request modeID: {0}", modeID),ModuleTraceSwitch.Sw.Info);
			}
			else
			{
				if (base.Request.Cookies[moduleCookie] != null)
				{
					modeID			=   Request.Cookies[moduleCookie].Value;
				if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml SetParameters from cookie modeID: {0}", modeID),ModuleTraceSwitch.Sw.Info);
				}
			}
			num1 = currentModeURL.IndexOf("ModeID=");
			if (num1 > 0)
			{
				currentModeURL		=   currentModeURL.Substring(0, (num1 - 1));
				currentURL			=   currentModeURL;
			}
			num1 = currentURL.IndexOf("EnhPageID=");
			if (num1 > 0)
			{
				currentURL			=   currentURL.Substring(0, (num1 - 1));
			}
			if (modeID == null)
			{
				modeID				=   "0";
			}
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml SetParameters modeID: {0}, currentURL:{1}", modeID,currentURL),ModuleTraceSwitch.Sw.Info);
		}
		#endregion

		#region auxiliary functions
		private string giveMePosition (string n)
		{
			if (n.Equals("1")) return "left";
			if (n.Equals("2")) return "center";
			if (n.Equals("3")) return "right";
			return "left";
		}

		private string giveMeUrl (string custom) 
		{
			// for compatibility with handler splitter
			string str	=	HttpUrlBuilder.BuildUrlWithCustomAttributes(DynPageLoc.Normal, PageID, ModuleID, custom);
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtml giveMeUrl url:{0}", str),ModuleTraceSwitch.Sw.Info);
			return str;
		}

		#endregion
		

		#region Std override

        public override void Page_PreInit(object sender, EventArgs e)
        {
			this.EditUrl = Config.ModulesPath+"/EnhancedHtml/EnhancedHtmlEdit.aspx";
            base.Page_PreInit(sender, e);
        }

		override protected void OnInit(EventArgs e)
		{

			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent() 
		{
			Load	+=new EventHandler(Page_Load);
		}

        #endregion
	}
}
